import React, {useRef} from 'react';
import {UploadOutlined} from '@ant-design/icons';
import {Button, message, Upload} from 'antd';
import ProForm, {ProFormInstance, ProFormSelect, ProFormText,} from '@ant-design/pro-form';
import {useRequest} from 'umi';
import {editUser, queryCurrent} from '../service';

import styles from './BaseView.less';
import {UploadProps} from "antd/es";
import ImgCrop from "antd-img-crop";
import {FileItem} from "@/pages/User/File/data";

const BaseView: React.FC = () => {
  // 获取用户基本信息
  const { data: currentUser, loading } = useRequest(() => {
    return queryCurrent();
  });

  // 获取用户头像
  const getAvatarURL = () => {
    if (currentUser) {
      if (currentUser.avatar) {
        return currentUser.avatar;
      }
      return 'https://gw.alipayobjects.com/zos/rmsportal/BiazfanxmamNRoxxVxka.png';
    }
    return '';
  };
  // Form更新入口
  const formRef = useRef<ProFormInstance>();

  // 头像上传
  let token = localStorage.getItem('token');
  const props: UploadProps = {

    name: 'file',
    action: '/api/upload?path=avatar',
    headers: {
      Authorization: `Bearer ${token}`,
    },
    onChange(info) {
      if (info.file.status === 'done') {

        // 上传动作已经完成
        console.log(info.file, info.fileList);
        if (info.file.response?.status === 'done') {
          formRef?.current?.setFieldsValue({
            avatar: info.file.response.path    // 可以绑定后台返回的path，或者fid，根据需求，取对应的数据
          })
          message.success('头像上传成功，请点下方提交保存更新（不提交不生效）！');
        } else {
          console.log("上传失败！", info.file)
          message.error(`${info.file.name} 上传失败！`);
        }
      }
    },

    // 上传进度条
    progress: {
      strokeColor: {
        '0%': '#108ee9',
        '100%': '#87d068',
      },
      strokeWidth: 3,
      format: percent => percent && `${parseFloat(percent.toFixed(2))}%`,
    },
  };

  // 头像组件 方便以后独立，增加裁剪之类的功能
  const AvatarView = ({ avatar }: { avatar: string }) => (
    <>
      <div className={styles.avatar_title}>头像</div>
      <div className={styles.avatar}>
        <img src={avatar} alt="avatar" />
      </div>
      <ImgCrop>
        <Upload {...props} showUploadList={false}>
          <div className={styles.button_view}>
            <Button>
              <UploadOutlined />
              更换头像
            </Button>
          </div>
        </Upload>
      </ImgCrop>
    </>
  );

  // 保存用户修改的数据
  const handleFinish = async (fields: FileItem) => {
    try {
      const res = await editUser({...fields});
      if(res && res.status === "done"){
        message.success(res.message);
        return true;
      }else {
        message.error(res.message);
        return false;
      }
    } catch (error) {
      message.error('添加失败请重试！');
      return false;
    }
  };

  return (
    <div className={styles.baseView}>
      {loading ? null : (
        <>
          <div className={styles.left}>
            <ProForm
              formRef={formRef}
              layout="vertical"
              onFinish={handleFinish}
              submitter={{
                resetButtonProps: {
                  style: {
                    display: 'none',
                  },
                },
                submitButtonProps: {
                  children: '更新基本信息',
                },
              }}
              initialValues={{
                ...currentUser,
              }}
            >
              <ProFormText
                width="md"
                name="username"
                label="账号"
                disabled={true}
              />
              <ProFormText
                width="md"
                name="nickName"
                label="姓名"
                rules={[
                  {
                    required: true,
                    message: '请输入您的昵称!',
                  },
                ]}
              />
              <ProFormSelect
                name="gender"
                label={"性别"}
                width="md"
                options={[
                  {value: 0, label: "女"},
                  {value: 1, label: "男"},
                  {value: 2, label: "未知"},
                ]}
                rules={[{required: true, message: '性别是必选项',},]}
              />
              <ProFormText
                width="md"
                name="email"
                label="邮箱"
                rules={[
                  {
                    required: true,
                    message: '请输入您的邮箱!',
                  },
                ]}
              />
              <ProFormText
                width="md"
                name="mobile"
                label="手机号码"
                rules={[
                  { pattern: /^((13\d)|(14[5,7])|(15[^4,\\D])|(17[0,1,3,6-8])|(18\d)|(19[8,9])|(166))\d{8}$/,
                    message:'手机号码格式不正确！'}
                ]}
              />
              <ProFormText name="avatar" width="md" hidden={true}/>
            </ProForm>
          </div>
          <div className={styles.right}>
            <AvatarView avatar={getAvatarURL()} />
          </div>
        </>
      )}
    </div>
  );
};

export default BaseView;
